package org.example.hospital_frontend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.hospital_frontend.common.BaseResponse;
import org.example.hospital_frontend.common.ErrorCode;
import org.example.hospital_frontend.common.ResultUtils;
import org.example.hospital_frontend.domain.User;
import org.example.hospital_frontend.exception.BusinessException;
import org.example.hospital_frontend.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/admin/users")
public class AdminUserController {

    @Resource
    private UserService userService;

    @GetMapping("/list")
    public BaseResponse<List<User>> listUsers(HttpServletRequest request) {
        // 检查用户是否登录且为管理员 (role = 1)
        User currentUser = (User) request.getSession().getAttribute("USER_LOGIN_STATE");
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        // 获取所有用户列表
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("role",0);
        List<User> userList = userService.list(queryWrapper);

        // TODO: 考虑到安全，可能需要对用户列表进行脱敏，移除敏感信息如密码等

        return ResultUtils.success(userList);
    }

    @PostMapping("/delete/{id}")
    public BaseResponse<Boolean> deleteUserById(@PathVariable Long id, HttpServletRequest request) {
        // 检查用户是否登录且为管理员 (role = 1)
        User currentUser = (User) request.getSession().getAttribute("USER_LOGIN_STATE");
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 检查ID是否有效
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        boolean result = userService.removeById(id);
        return ResultUtils.success(result);
    }

    /**
     * 根据ID获取用户详细信息 (管理员)
     *
     * @param id 用户ID
     * @param request HttpServletRequest
     * @return 用户详细信息
     */
    @GetMapping("/{id}")
    public BaseResponse<User> getUserById(@PathVariable Long id, HttpServletRequest request) {
        // 检查用户是否登录且为管理员 (role = 1)
        User currentUser = (User) request.getSession().getAttribute("USER_LOGIN_STATE");
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 检查ID是否有效
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User user = userService.getById(id);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }
        // TODO: 考虑到安全，可能需要对用户数据进行脱敏，移除敏感信息如密码等

        return ResultUtils.success(user);
    }

    /**
     * 更新用户信息 (管理员)
     *
     * @param user 包含更新信息的User对象
     * @param request HttpServletRequest
     * @return 是否更新成功
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateUser(@RequestBody User user, HttpServletRequest request) {
        // 检查用户是否登录且为管理员 (role = 1)
        User currentUser = (User) request.getSession().getAttribute("USER_LOGIN_STATE");
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 检查用户ID是否有效
        if (user == null || user.getId() == null || user.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // TODO: 可以添加更多更新前的验证，例如检查字段的合法性
        // 确保管理员不能通过这个接口修改自己的角色或删除自己？可能需要根据需求决定

        boolean result = userService.updateById(user);
        return ResultUtils.success(result);
    }

    /**
     * 管理员添加新用户（支持所有字段）
     */
    @PostMapping("/add")
    public BaseResponse<Long> addUserByAdmin(@RequestBody User user, HttpServletRequest request) {
        // 1. 权限校验（必须是管理员）
        User currentUser = (User) request.getSession().getAttribute("USER_LOGIN_STATE");
        if (currentUser == null ) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限");
        }
        // 2. 必填项校验
        if (user.getUsername() == null || user.getPassword() == null || user.getNickname() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号、密码、昵称为必填项");
        }
        // 3. 检查用户名唯一
        if (userService.count(new QueryWrapper<User>().eq("username", user.getUsername())) > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该用户名已存在");
        }


        // 4. 保存用户
        boolean result = userService.save(user);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "添加用户失败");
        }
        return ResultUtils.success(user.getId().longValue());
    }
} 